<template>
  <div class="allocMenuIndex">
    <el-card>
      <div>
        <div slot="header" class="clearfix">
          分配资源
        </div>
        <el-tree
          :data="menus"
          :props="defaultProps"
          @node-click="handleNodeClick"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          :default-checked-keys="defaultSelect"
        ></el-tree>
        <div
          style="display:flex;justify-content:center;align-items:center;
       padding:50px;"
        >
          <el-button @click="reset">清空</el-button>
          <el-button type="primary" @click="onSave">保存</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getResourceNodeList, allocateRoleResources, getRoleResources } from './api/index'
export default Vue.extend({
  name: 'allocResourceIndex',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  async created () {
    console.log(this.roleId)
    await this.getResourceNodeList()
    await this.getRoleResources()
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      defaultSelect: []
    }
  },
  methods: {
    handleNodeClick (data) {
      console.log(data)
    },
    async getResourceNodeList () {
      const { data } = await getResourceNodeList()
      console.log(data)
      if (data.code === '000000') {
        this.menus = data.data
      }
    },
    async onSave () {
      console.log('save')
      console.log()
      const { data } = await allocateRoleResources({
        roleId: this.roleId,
        menuIdList: this.$refs.tree.getCheckedKeys()
      })
      if (data.code === '000000') {
        this.$message.success('添加成功')
        this.$router.go(-1)
      }
    },
    async getRoleResources () {
      const { data } = await getRoleResources(this.roleId)
      console.log(data)
      const arr = []
      const selectId = (array: Array<any>) => {
        array.forEach(ele => {
          arr.push(ele.id)
          if (ele.subMenuList) {
            selectId(ele.subMenuList)
          }
        })
      }
      selectId(data.data)
      this.defaultSelect = arr
      console.log(this.defaultSelect)
    },
    async reset () {
      this.$refs.tree.setCheckedKeys([])
    }
  }
})
</script>

<style lang="scss" scoped></style>
